﻿using System;
using System.Windows;
using ClientBankWPF.Service;
using DevExpress.Xpf.Core;
using ClientBankWPF.Entities;

namespace ClientBankWPF
{
    /// <summary>
    /// Interaction logic for BankAddWindow.xaml
    /// </summary>
    public partial class BankAddWindow
    {
        private readonly DataAccessService dataAccessService;
        private readonly Generators generators;

        public Bank NewBank { get; set; }

        public BankAddWindow()
        {
            InitializeComponent();
        }

        public BankAddWindow(DataAccessService dataAccessService)
        {
            InitializeComponent();
            this.dataAccessService = dataAccessService;
            generators = new Generators(dataAccessService);
            textBoxBankCode.Text = generators.BankCodeGenerator().ToString();
        }

        private void ButtonCreateBankClick(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!String.IsNullOrEmpty(textBoxBankName.Text))
                {
                    NewBank = dataAccessService.GetBank(textBoxBankName.Text);
                    if (NewBank != null)
                    {
                        DXMessageBox.Show("Такой банк уже существует", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                        NewBank = null;
                        return;
                    }
                    NewBank = new Bank
                    {
                        Id = Guid.NewGuid(),
                        Code = Decimal.Parse(textBoxBankCode.Text),
                        Name = textBoxBankName.Text,
                    };
                    string result = dataAccessService.AddBank(NewBank);
                    if (!String.IsNullOrEmpty(result))
                    {
                        DXMessageBox.Show(result, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                    else
                    {
                        DXMessageBox.Show("Банк добавлен", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
                        textBoxBankCode.Text = generators.BankCodeGenerator().ToString();
                        textBoxBankName.Text = "";
                        Close();
                    }
                }
                else
                {
                    DXMessageBox.Show("Имя банка не введено", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception exception)
            {
                DXMessageBox.Show(exception.Message, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void ButtonCancelClick(object sender, RoutedEventArgs e)
        {
            Close();
        }
    }
}
